import 'package:OASys/api/MenuApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/components/scaffoldItem.dart';
import 'package:OASys/entity/MenuBool.dart';
import 'package:OASys/entity/MenuTreeVo.dart';
import 'package:OASys/entity/MenuVo.dart';
import 'package:OASys/utils/strUtils.dart';
import 'package:flutter/material.dart';

class MenuPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScaffoldItem('权限管理', MyMenuPage());
  }
}

class MyMenuPage extends StatefulWidget {
  @override
  _MyMenuPageState createState() => _MyMenuPageState();
}

class _MyMenuPageState extends State<MyMenuPage> {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  List<bool> dataList = List.generate(3, (index) => false).toList();
  List<bool> subDataList = List.generate(3, (index) => false).toList();

  MenuVo info = new MenuVo();
  List<MenuBool> boolList;
  List<MenuTreeVo> menuTree;
  @override
  void initState() {
    super.initState();
    _getTree();
  }

  void _getTree() {
    MenuApi().tree(
      success: (res) {
        setState(() {
          menuTree = res;
          res.forEach((element) {
            print(element.toJson().toString());
          });
          boolList = _getBoolList(menuTree);
        });
      },
      error: (err) {
        print(err);
      },
    );
  }

  List<MenuBool> _getBoolList(List<MenuTreeVo> menuTree) {
    List<MenuBool> boolList = [];
    int index = 0;
    menuTree.forEach((element) {
      MenuBool menuBool = new MenuBool();
      menuBool.flag = false;
      menuBool.index = index;
      index++;
      if (element.children != null) {
        menuBool.childen = _getBoolList(element.children);
      }
      boolList.add(menuBool);
    });
    return boolList;
  }

  // 保存操作
  void doSave(context, int id, bool isAdd) {
    var form = formKey.currentState;
    form.save();
    setState(() {
      if (isAdd) {
        info.parentId = id;
        info.id = null;
      } else {
        info.parentId = null;
        info.id = id;
      }
    });

    MenuApi().save(
      info,
      success: (res) {
        setState(() {
          _getTree();
        });
        Navigator.of(context).pop();
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  // 删除操作
  void doRemove(int id) {}
  // 表单重置
  void reset() {
    var form = formKey.currentState;
    form.reset();
  }

  showSave(MenuTreeVo menuTreeVo, int parentId) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              menuTreeVo != null ? '编辑权限' : '新增权限',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              width: 300,
              child: Form(
                key: formKey,
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier("权限名:"),
                        Container(
                          width: 200,
                          child: FormInput(
                            initValue:
                                menuTreeVo != null ? menuTreeVo.name : '',
                            hintText: "请输入权限名",
                            onSave: (value) {
                              info.name = value;
                            },
                          ),
                        )
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier("路由名:"),
                        Container(
                          width: 200,
                          child: FormInput(
                            initValue:
                                menuTreeVo != null ? menuTreeVo.route : '',
                            hintText: "请输入路由名",
                            onSave: (value) {
                              info.route = value;
                            },
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          actions: <Widget>[
            RaisedButton(
              color: Color.fromRGBO(33, 150, 243, 1),
              child: Text('保 存'),
              onPressed: () {
                doSave(context, menuTreeVo == null ? parentId : menuTreeVo.id,
                    menuTreeVo == null);
              },
            ),
            RaisedButton(
              color: Color.fromRGBO(245, 108, 108, 1),
              child: Text('重 置'),
              onPressed: reset,
            ),
          ],
        );
      },
    );
  }

  // 显示信息
  showInfo(MenuTreeVo item) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          titlePadding: EdgeInsets.all(0),
          title: Container(
            height: 50,
            alignment: Alignment.center,
            child: Text(
              '权限信息',
              style: TextStyle(color: Colors.white),
            ),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(3),
                topRight: Radius.circular(3),
              ),
            ),
          ),
          contentPadding: EdgeInsets.all(0),
          content: Container(
            height: 300,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromRGBO(250, 250, 250, 1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Container(
              margin: EdgeInsets.only(
                top: 20,
                bottom: 20,
              ),
              height: 260,
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(
                  children: [
                    InfoItem('权限名',
                        StrUtils.isNotBlank(item.name) ? item.name : "无"),
                    SizedBox(height: 5),
                    InfoItem('路由名', item.route),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        child: _buildExpansionPanelList(menuTree, boolList),
      ),
    );
  }

  _buildExpansionPanelList(List<MenuTreeVo> menuTree, List<MenuBool> boolList) {
    if (boolList == null) {
      return null;
    }
    return ExpansionPanelList(
      expansionCallback: (index, isExpanded) {
        setState(() {
          boolList[index].flag = !isExpanded;
        });
      },
      children: boolList.map((item) {
        return ExpansionPanel(
          isExpanded: item.flag,
          headerBuilder: (context, isExpanded) {
            return FlatButton(
              child: Text(menuTree[item.index].name),
              onPressed: () {
                showInfo(menuTree[item.index]);
              },
            );
          },
          body: Column(
            children: [
              Container(
                padding: EdgeInsets.all(10),
                child: _buildExpansionPanelList(
                    menuTree[item.index].children, item.childen),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  RaisedButton(
                    color: Color.fromRGBO(103, 194, 58, 1),
                    child: Text(
                      '添 加',
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: () {
                      showSave(null, menuTree[item.index].id);
                    },
                  ),
                  RaisedButton(
                    color: Color.fromRGBO(33, 150, 243, 1),
                    child: Text(
                      '编 辑',
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: () {
                      showSave(menuTree[item.index], null);
                    },
                  ),
                  RaisedButton(
                    color: Color.fromRGBO(245, 108, 108, 1),
                    child: Text(
                      '删 除',
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: () {
                      doRemove(menuTree[item.index].id);
                    },
                  ),
                ],
              ),
              SizedBox(
                height: 10,
              ),
            ],
          ),
        );
      }).toList(),
    );
  }
}
